<template>
  <div class="user-center-page">
    <div class="page-header">
      <h2>个人中心</h2>
      <el-button type="primary" @click="$router.push('/')">
        <el-icon><Back /></el-icon>返回首页
      </el-button>
    </div>

    <!-- 用户信息卡片 -->
    <el-card class="user-info-card">
      <div class="user-card-content">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar" />
        </div>

        <div class="user-info">
          <div class="user-name-container">
            <h3>{{ userInfo.name }}</h3>
            <el-button
              class="edit-name-btn"
              type="primary"
              link
              @click="showEditName"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <p class="user-department">
            {{ userInfo.department }} {{ userInfo.clazz }}
          </p>
          <p class="user-bio">
            {{ userInfo.bio || "这个人很懒，什么都没有留下..." }}
          </p>

          <div class="user-stats">
            <span>发布: {{ userStats.posts }}</span>
            <span>帮助: {{ userStats.helps }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加昵称编辑对话框 -->
    <el-dialog
      v-model="nameDialogVisible"
      title="修改昵称"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="nameForm" :rules="nameRules" ref="nameFormRef">
        <el-form-item prop="name">
          <el-input
            v-model="nameForm.name"
            placeholder="请输入新昵称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="nameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateName" :loading="updating"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 用户中心主要内容 - 改为左侧导航 + 路由视图 -->
    <el-card class="user-content-card">
      <div class="user-center-container">
        <!-- 左侧导航菜单 -->
        <div class="user-center-sidebar">
          <el-menu :default-active="activeMenu" class="user-center-menu" router>
            <el-menu-item index="/user/profile">
              <el-icon><UserFilled /></el-icon>
              <span>基本资料</span>
            </el-menu-item>
            <el-menu-item index="/user/avatar">
              <el-icon><Picture /></el-icon>
              <span>头像设置</span>
            </el-menu-item>
            <el-menu-item index="/user/posts">
              <el-icon><Document /></el-icon>
              <span>我的发布</span>
            </el-menu-item>
            <el-menu-item index="/user/notifications">
              <el-icon><Bell /></el-icon>
              <span>消息通知</span>
            </el-menu-item>
            <el-menu-item index="/user/security">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 右侧内容区域 - 路由视图 -->
        <div class="user-center-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component
                :is="Component"
                :user-info="userInfo"
                :user-id="userInfo.id"
                @update-profile="updateUserInfo"
                @update-avatar="updateAvatar"
              />
            </transition>
          </router-view>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { reactive, computed, ref, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import {
  Back,
  UserFilled,
  Picture,
  Document,
  Bell,
  Lock,
  Edit,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import api from "@/utils/api";

export default {
  name: "UserCenter",
  components: {
    Back,
    UserFilled,
    Picture,
    Document,
    Bell,
    Lock,
    Edit,
  },
  setup() {
    // 添加默认头像URL
    const defaultAvatar = ref(
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
    );

    const route = useRoute();

    // 计算当前激活的菜单项
    const activeMenu = computed(() => route.path);

    const userInfo = ref({
      name: "",
      department: "",
      clazz: "",
      bio: "",
      avatar: "",
    });

    const userStats = reactive({
      posts: 0,
      helps: 0,
    });

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await api.get("/user/profile");
        if (response.data.code === 200) {
          userInfo.value = response.data.data;
          // 确保avatar属性存在
          if (!userInfo.value.avatar) {
            userInfo.value.avatar = ""; // 设置为空字符串而不是undefined
          }
          console.log("UserCenter fetched userInfo:", userInfo.value);
        } else {
          ElMessage.error(response.data.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        ElMessage.error("获取用户信息失败，请稍后再试");
      }
    };

    // 获取用户统计数据
    const fetchUserStats = async () => {
      try {
        const response = await api.get("/user/stats");
        if (response.data.code === 200) {
          userStats.posts = response.data.data.posts || 0;
          userStats.helps = response.data.data.helps || 0;
        } else {
          ElMessage.error(response.data.message || "获取用户统计数据失败");
        }
      } catch (error) {
        console.error("获取用户统计数据失败:", error);
        ElMessage.error("获取用户统计数据失败，请稍后再试");
      }
    };

    // 1. 添加事件监听更新头像
    const handleAvatarUpdate = (event) => {
      if (event.detail && event.detail.avatar) {
        console.log("UserCenter 收到头像更新事件:", event.detail.avatar);
        // 直接更新用户头像
        userInfo.value.avatar = event.detail.avatar;
      }
    };

    // 2. 添加挂载和卸载时的事件监听器
    onMounted(() => {
      // 现有的 onMounted 代码
      fetchUserInfo();
      fetchUserStats();

      // 添加事件监听
      window.addEventListener("userAvatarUpdated", handleAvatarUpdate);
    });

    onUnmounted(() => {
      // 移除事件监听
      window.removeEventListener("userAvatarUpdated", handleAvatarUpdate);
    });

    // 3. 增强 updateAvatar 方法
    const updateAvatar = (data) => {
      if (data && data.avatar) {
        console.log("头像更新:", data.avatar);
        userInfo.value.avatar = data.avatar;

        // 在本地存储中也更新用户头像，确保页面刷新后也能保持
        try {
          const storedUserInfo = JSON.parse(
            localStorage.getItem("userInfo") || "{}"
          );
          storedUserInfo.avatar = data.avatar;
          localStorage.setItem("userInfo", JSON.stringify(storedUserInfo));
        } catch (error) {
          console.error("更新本地存储中的头像失败:", error);
        }

        // 触发全局头像更新事件
        const event = new CustomEvent("userAvatarUpdated", {
          detail: { avatar: data.avatar },
        });
        window.dispatchEvent(event);

        // 可选：强制重新获取用户信息（如果有必要）
        // setTimeout(() => {
        //   fetchUserInfo();
        // }, 300);
      }
    };

    const updateUserInfo = (newInfo) => {
      const updatedInfo = { ...newInfo };
      delete updatedInfo.name;

      Object.assign(userInfo.value, updatedInfo);
    };

    // 昵称修改相关
    const nameDialogVisible = ref(false);
    const nameFormRef = ref(null);
    const updating = ref(false);
    const nameForm = reactive({
      name: "",
    });
    const nameRules = {
      name: [
        { required: true, message: "请输入昵称", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "昵称长度在2到20个字符之间",
          trigger: "blur",
        },
      ],
    };

    // 显示昵称编辑对话框
    const showEditName = () => {
      nameForm.name = userInfo.value.name;
      nameDialogVisible.value = true;
    };

    // 更新昵称
    const updateName = async () => {
      if (!nameFormRef.value) return;

      try {
        await nameFormRef.value.validate();

        updating.value = true;
        try {
          const response = await api.put("/user/profile/name", {
            name: nameForm.name,
          });

          if (response.data.code === 200) {
            ElMessage.success("昵称修改成功");
            userInfo.value.name = nameForm.name;
            nameDialogVisible.value = false;
          } else {
            ElMessage.error(response.data.message || "修改失败");
          }
        } catch (error) {
          console.error("修改昵称失败:", error);
          ElMessage.error("修改失败，请稍后再试");
        } finally {
          updating.value = false;
        }
      } catch (error) {
        // 表单验证失败
      }
    };

    return {
      activeMenu,
      userInfo,
      userStats,
      updateUserInfo,
      updateAvatar,
      nameDialogVisible,
      nameFormRef,
      nameForm,
      nameRules,
      updating,
      showEditName,
      updateName,
      defaultAvatar,
      handleAvatarUpdate,
    };
  },
};
</script>

<style scoped>
.user-center-page {
  padding: 0;
  width: 100%;
  max-width: none;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 22px;
}

.user-info-card {
  margin-bottom: 20px;
  width: 100%;
}

.user-card-content {
  display: flex;
  align-items: center;
  gap: 30px;
}

.avatar-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.user-info {
  flex: 1;
}

.user-info h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: var(--text-primary);
}

.user-department,
.user-bio {
  margin: 5px 0;
  color: var(--text-secondary);
}

.user-stats {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.user-stats span {
  display: inline-block;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: var(--text-secondary);
}

.user-content-card {
  margin-bottom: 20px;
  width: 100%;
}

.user-center-container {
  display: flex;
  min-height: 600px;
}

.user-center-sidebar {
  width: 200px;
  border-right: 1px solid var(--border-color);
}

.user-center-menu {
  height: 100%;
  border-right: none;
}

.user-center-content {
  flex: 1;
  padding: 20px;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-width: 850px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 添加昵称编辑相关样式 */
.user-name-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-name-container h3 {
  margin: 0;
}

.edit-name-btn {
  padding: 2px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  gap: 10px;
}
</style> 